package cn.zhentao.interceptor;

import cn.zhentao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 权限拦截器
 * 拦截接口请求并校验用户权限（适配JDK 17）
 */
@Component
public class PermissionInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 从Spring Security上下文获取当前登录用户ID（推荐方式）
        Long userId = getCurrentUserId();
        if (userId == null) {
            sendError(response, "请先登录");
            return false;
        }

        // 2. 获取请求路径和方法
        String requestURI = request.getRequestURI();
        String method = request.getMethod();

        // 3. 校验用户是否有权限访问该接口
        boolean hasPermission = userService.hasPermission(userId, requestURI, method);
        if (!hasPermission) {
            sendError(response, "没有访问权限");
            return false;
        }

        return true; // 有权限，放行
    }

    /**
     * 从Security上下文获取当前登录用户ID
     * 替代从请求头获取的方式，更安全可靠
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return null;
        }

        // 假设用户信息存储在Principal中，实际类型需与UserDetails实现类匹配
        Object principal = authentication.getPrincipal();
        if (principal instanceof cn.zhentao.pojo.User) {
            return ((cn.zhentao.pojo.User) principal).getId();
        }

        return null;
    }

    /**
     * 发送JSON格式的错误响应
     */
    private void sendError(HttpServletResponse response, String message) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        // 使用try-with-resources自动关闭流
        try (var writer = response.getWriter()) {
            writer.write("{\"code\":403,\"message\":\"" + message + "\"}");
        }
    }
}
